package com.appengine.news.service;

import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.appengine.news.entity.RssImageEntity;
import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.Transform;

@SuppressWarnings("serial")
public class ImageService extends AbstractService{
	private static final Logger log = Logger.getLogger(ImageService.class
			.getName());	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		log.entering(ImageService.class.getName(), "doGet");
		String attribute = req.getPathInfo();				
		if (attribute == null) {
			resp.setContentType("image/jpg");
			resp.sendRedirect("/dummy.jpg");
			return;
		}
		else
		{
			attribute=attribute.replaceFirst("/", "");
			int lastIndexOf = attribute.lastIndexOf(".");
			if(lastIndexOf>0)
			{
				attribute=attribute.substring(0,lastIndexOf);
			}
		}

		final PersistenceManager pm = getPersistenceManager();
		final String query = "select from " + RssImageEntity.class.getName()
				+ " where id==" + attribute;
		final List<RssImageEntity> execute = (List<RssImageEntity>) pm.newQuery(query)
				.execute();

		if (execute.isEmpty()) {
			resp.setContentType("image/jpg");
			resp.sendRedirect("/dummy.jpg");
		} else {
			final RssImageEntity image = execute.get(0);
			final Blob blob = image.getImageData();
			byte[] bytes = blob.getBytes();
			
			final ImagesService imagesService = ImagesServiceFactory.getImagesService();
	        final Image oldImage = ImagesServiceFactory.makeImage(bytes);			
			resp.setContentType("image/"+oldImage.getFormat().name());		
			
			final Image resize = resize(imagesService,oldImage);
			final byte[] imageData = resize.getImageData();
			
			resp.setContentLength(imageData.length);
			final ServletOutputStream outputStream = resp.getOutputStream();
			outputStream.write(imageData);
		}
		log.exiting(ImageService.class.getName(), "doGet");
	}
	/**
	 * Resize image
	 * @param imagesService
	 * @param oldImage
	 * @return
	 */
	private Image resize(ImagesService imagesService, Image oldImage)
	{        
		log.entering(ImageService.class.getName(), "resize");
        int height = oldImage.getHeight();
        int width = oldImage.getWidth();      
        
        int j = 500;
        Transform resize;
		if((height>j) || (width>j))
        {    
			if(height>j)
			{
				int i = height/j;	        	
	            resize = ImagesServiceFactory.makeResize(width/i, j);	            
			}
			else
			{
				int i = width/j;	        	
	            resize = ImagesServiceFactory.makeResize(j,height/i);
			}
        	final Image newImage = imagesService.applyTransform(resize, oldImage);
            return newImage;
        }
		log.exiting(ImageService.class.getName(), "resize");
        return oldImage; 	        
	}	
}
